<script lang="ts" setup>
  import { computed, ref } from 'vue'
  import { NButton, NInput, NPopconfirm, useMessage } from 'naive-ui'
  import { SvgIcon } from '@/components/common'
  import { useUserStore } from '@/stores'
  import type { UserInfo } from '@/stores/modules/user/helper'
  import { getCurrentDate } from '@/utils/functions'

  const userStore = useUserStore()

  const ms = useMessage()

  const userInfo = computed(() => userStore.userInfo)

  const avatar = ref(userInfo.value.avatar ?? '')

  const name = ref(userInfo.value.name ?? '')

  const description = ref(userInfo.value.description ?? '')

  function updateUserInfo(options: Partial<UserInfo>) {
    userStore.updateUserInfo(options)
    ms.success('操作成功')
  }

  function handleReset() {
    userStore.resetUserInfo()
    ms.success('操作成功')
    window.location.reload()
  }

  function exportData(): void {
    const date = getCurrentDate()
    const data: string = localStorage.getItem('chatStorage') ?? '{}'
    const jsonString: string = JSON.stringify(JSON.parse(data), null, 2)
    const blob: Blob = new Blob([jsonString], { type: 'application/json' })
    const url: string = URL.createObjectURL(blob)
    const link: HTMLAnchorElement = document.createElement('a')
    link.href = url
    link.download = `chat-store_${date}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  function importData(event: Event): void {
    const target = event.target as HTMLInputElement
    if (!target?.files) return

    const file: File = target.files[0]
    if (!file) return

    const reader: FileReader = new FileReader()
    reader.onload = () => {
      try {
        const data = JSON.parse(reader.result as string)
        localStorage.setItem('chatStorage', JSON.stringify(data))
        ms.success('操作成功')
        location.reload()
      } catch (error) {
        console.error(error)
        ms.error('非法的文件格式')
      }
    }
    reader.readAsText(file)
  }

  function clearData(): void {
    localStorage.removeItem('chatStorage')
    location.reload()
  }

  function handleImportButtonClick(): void {
    const fileInput = document.getElementById('fileInput') as HTMLElement
    if (fileInput) fileInput.click()
  }
</script>

<template>
  <div class="p-4 space-y-5 min-h-[200px]">
    <div class="space-y-6">
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">头像</span>
        <div class="flex-1">
          <NInput v-model:value="avatar" placeholder="" />
        </div>
        <NButton size="tiny" text type="primary" @click="updateUserInfo({ avatar })">
          保存
        </NButton>
      </div>
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">名称</span>
        <div class="w-[200px]">
          <NInput v-model:value="name" placeholder="" />
        </div>
        <NButton size="tiny" text type="primary" @click="updateUserInfo({ name })"> 保存 </NButton>
      </div>
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">描述</span>
        <div class="flex-1">
          <NInput v-model:value="description" placeholder="" />
        </div>
        <NButton size="tiny" text type="primary" @click="updateUserInfo({ description })">
          保存
        </NButton>
      </div>
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">聊天记录</span>

        <div class="flex flex-wrap items-center gap-4">
          <NButton size="small" @click="exportData">
            <template #icon>
              <SvgIcon icon="ri:download-2-fill" />
            </template>
            导出
          </NButton>

          <input id="fileInput" type="file" style="display: none" @change="importData" />
          <NButton size="small" @click="handleImportButtonClick">
            <template #icon>
              <SvgIcon icon="ri:upload-2-fill" />
            </template>
            导入
          </NButton>

          <NPopconfirm placement="bottom" @positive-click="clearData">
            <template #trigger>
              <NButton size="small">
                <template #icon>
                  <SvgIcon icon="ri:close-circle-line" />
                </template>
                清空
              </NButton>
            </template>
            确定清空记录?
          </NPopconfirm>
        </div>
      </div>
      <!-- <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">主题</span>
        <div class="flex flex-wrap items-center gap-4">
          <template v-for="item of themeOptions" :key="item.key">
            <NButton
              size="small"
              :type="item.key === theme ? 'primary' : undefined"
              @click="appStore.setTheme(item.key)"
            >
              <template #icon>
                <SvgIcon :icon="item.icon" />
              </template>
            </NButton>
          </template>
        </div>
      </div> -->
      <!-- <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">语言</span>
        <div class="flex flex-wrap items-center gap-4">
          <NSelect
            style="width: 140px"
            :value="language"
            :options="languageOptions"
            @update-value="(value) => appStore.setLanguage(value)"
          />
        </div>
      </div> -->
      <div class="flex items-center space-x-4">
        <span class="flex-shrink-0 w-[100px]">重置用户信息</span>
        <NButton size="small" @click="handleReset"> 重置 </NButton>
      </div>
    </div>
  </div>
</template>
